<template>
    <h3>上传头像</h3>
    <el-upload class="avatar-uploader" action="http://uc.qiniuapi.com" :show-file-list="false"
        :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" :width="178" :height="178"  />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
    </el-upload>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import request from '@/request'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

function upoloadImg (rawFile : File) {
    const formData = new FormData()
    formData.append('file', rawFile)
    // request 发起请求
    request.post('http://127.0.0.1:8000/users/qiniu_token/', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(res => {
        console.log("res>>>>>", res.data.url)
        imageUrl.value = res.data.url
    }).catch(err => {
        console.log("err>>>>>", err)
    })
}

// 上传前对图片校验，图片的格式和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log("rawFile>>>>>>", rawFile)
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    // 校验完成调用上传的方法
    upoloadImg(rawFile)
    return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
